import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api";
import { setToken, getToken, removeToken } from "@/utils/token";
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit("GETCODE", result.data);
            return "ok";
        } else {
            return Promise.reject(new Error("获取验证码失败！"));
        }
    },
    //注册用户
    async userRegister({ commit }, data) {
        let result = await reqUserRegister(data);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error("注册用户失败！"));
        }
    },
    //用户登录
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        console.log(result)
        if (result.code == 200) {
            commit("USERLOGIN", result.data.token);
            //持久化存储token
            setToken(result.data.token);
            return "ok";
        } else {
            return Promise.reject(new Error("用户登录失败！"));
        }
    },
    //获取用户信息
    async userInfo({ commit }) {
        let result = await reqUserInfo();
        if (result.code == 200) {
            commit("USERINFO", result.data);
            return "ok";
        } else {
            return Promise.reject(new Error("获取用户信息失败！"));
        }
    },
    //退出登录
    async userLogout({ commit }) {
        let result = await reqLogout();
        if (result.code == 200) {
            commit("USERLOGOUT");
            return "ok";
        } else {
            return Promise.reject(new Error("退出登录失败！"));
        }
    }
}
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    USERLOGOUT(state) {
        state.token = '';
        state.userInfo = {};
        removeToken();
    }
}
const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}
const getters = {}

export default {
    namespaced: true,
    actions,
    mutations,
    state,
    getters
}